package net.pimpas.web.jsf.renderers.ajax.populate.autoupdate.html;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import net.pimpas.web.jsf.components.ajax.UIAjax;
import net.pimpas.web.jsf.components.ajax.populate.autoupdate.UIAjaxPopulateAutoUpdate;
import net.pimpas.web.jsf.renderers.ajax.populate.html.HtmlAjaxPopulateRenderer;
import net.pimpas.web.jsf.util.ComponentUtils;

import org.apache.myfaces.shared_impl.renderkit.html.HTML;

public class HtmlAjaxPopulateAutoUpdateRenderer extends HtmlAjaxPopulateRenderer {
	
	@SuppressWarnings("unchecked")
	@Override
	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
		if(!component.isRendered()) return;
		if(!ComponentUtils.isCorrectComponentType(component, UIAjaxPopulateAutoUpdate.class)) return;
		
		super.initResourceManager(context, component);
		
		UIAjaxPopulateAutoUpdate populate = (UIAjaxPopulateAutoUpdate) component;
		
		String controlId = null;
		if(populate.getControl() != null) {
			UIComponent control = ComponentUtils.getComponentById(context.getViewRoot(), context, populate.getControl(), ComponentUtils.SERVER_ID);
			if(control != null) controlId = "'"+control.getClientId(context)+"'";
		}
		
		ResponseWriter writer = context.getResponseWriter();
			
		writer.startElement(HTML.SPAN_ELEM, component);
		writer.writeAttribute(HTML.ID_ATTR, component.getClientId(context), null);
		writer.endElement(HTML.SPAN_ELEM);
		
		writer.startElement(HTML.SCRIPT_ELEM, component);
		writer.write("new pimpas.Interval(" + populate.getTimer()+", function() {pimpas.AJAX.Populate.ProcessAJAX.execute(pimpas.DOM.getElement('"+component.getClientId(context)+"'), "+populate.getAsync().booleanValue()+", " + populate.getImmediate().booleanValue()+", " + populate.getSendForm().booleanValue()+
				", "+controlId+", [{name: '"+component.getClientId(context)+"', value: ''}," +
						"{name: '"+UIAjax.AJAX_OBJECT_REQUEST_KEY+"', value: '"+component.getClientId(context)+"'}]);}, null).go()");
		writer.endElement(HTML.SCRIPT_ELEM);
	}
}